<?php

namespace app\common\lib\redis;

use think\Exception;

class Redis
{
    public $redis = "";
    private static $_instance = null;

    //单例模式
    public static function getInstance()
    {
        if (empty(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function __construct()
    {
        $this->redis = new \Redis();
        $result = $this->redis->connect(config('redis.host'), config('redis.port'), config('redis.time_out'));
        if ($result === false) {
            throw  new Exception('redis连接失败');
        }
    }

    /**
     * redis set
     * @param $key
     * @param $value
     * @param int $time
     * @return bool|string
     */
    public function set($key, $value, $time = 0)
    {
        if (!$key) {
            return '';
        }
        if (is_array($value)) {
            $value = json_encode($value, JSON_UNESCAPED_UNICODE);
        }
        if (!$time) {
            return $this->redis->set($key, $value);
        }
        return $this->redis->setex($key, $time, $value);
    }

    /**
     * redis get
     * @param $key
     * @return bool|string
     */
    public function get($key)
    {
        if (!$key) {
            return '';
        }
        return $this->redis->get($key);
    }

    /**
     *  key 是否存在
     * @param $key
     */
    public function exists($key)
    {
        if ($this->redis->exists($key)) {
            return true;
        }
        return false;
    }

    /**
     * 设置过期时间
     * @param $key
     * @param int $time
     */
    public function expire($key, $time = 0)
    {
        $this->redis->expire($key, $time);
    }

    /**
     * 自增
     * @param $key
     * @param int $step
     */

    public function incr($key,$step = 1)
    {
        if ($step == 1) {
            return $this->redis->incr($key);
        } else {
            return $this->redis->incrBy($key, $step);
        }
    }

    /**
     * 自减
     * @param $key
     * @param int $step
     * @return int
     */

    public function decr($key, $step = 1)
    {
        if ($step == 1) {
            return $this->redis->decr($key);
        } else {
            return $this->redis->decrBy($key, $step);
        }
    }
}